package com.maimang.platform.dsp.controller;

import com.alibaba.fastjson.JSONObject;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.config.Global;
import com.maimang.platform.common.utils.RedisUtils;
import com.maimang.platform.dsp.constant.TokenUrl;
import com.maimang.platform.dsp.utils.ApiService;
import com.maimang.platform.enums.Status;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.tool.ToolIP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname AccessController
 * @description <br>账户授权服务</br>
 * @date 2019-08-08 17:27
 * @email jintaozhao@qq.com
 */
@RestController
@RequestMapping("/oauth2")
public class AccessController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AccessController.class);

	@Autowired
	private ApiService apiService;

	/**
	 * 今日头条授权回调
	 *
	 * @param authCode 授权返回的auth_code
	 * @param state    传递的自定义参数，这里我们构建授权URL时传递的是advertiser_id，理论上是不会为空的
	 * @return
	 */
	@GetMapping("/callback")
	public Result oauthCallback(HttpServletRequest request, @RequestParam("auth_code") String authCode, @RequestParam("state") String state) {
		String key = "auth_code";

		if (StringUtils.isNotEmpty(state)) {
			key += ("_" + state);
		}

		if (StringUtils.isNotEmpty(authCode)) {
			RedisUtils.set(key, authCode, 10 * 60);
		}

		String ip = ToolIP.getIpAddr(request);
		logger.info(StringUtils.format("收到来自[{}]的授权回调,[auth_code={},state={}]", ip, authCode, state));
		return Result.SUCCESS(Status.success);
	}

	/**
	 * 获取access_token
	 *
	 * @return
	 */
	@PostMapping("/access_token")
	@ResponseBody
	public boolean getAccessToken() {
		Map param = new HashMap();
		param.put("app_id", Global.getConfig("app_id"));
		param.put("secret", Global.getConfig("secret"));
		param.put("grant_type", "auth_code");
		String authCodeKey = "auth_code";
		param.put("auth_code", RedisUtils.get(authCodeKey));

		JSONObject resultObject = apiService.sendPost(TokenUrl.ACCESS_TOKEN, param);
		return handleResult(resultObject);
	}


	/**
	 * 刷新access_token
	 *
	 * @return
	 */
	@PostMapping("/refresh_token")
	@ResponseBody
	public boolean getRefreshToken() {
		Map param = new HashMap();
		param.put("app_id", Global.getConfig("app_id"));
		param.put("secret", Global.getConfig("secret"));
		param.put("grant_type", "refresh_token");
		String refreshKey = "refresh_token";
		param.put("refresh_token", RedisUtils.get(refreshKey));

		JSONObject resultObject = apiService.sendPost(TokenUrl.REFRESH_TOKEN, param);
		return handleResult(resultObject);
	}

	/**
	 * 解析处理结果
	 *
	 * @param resultObject 请求结果对象
	 * @return
	 */
	private boolean handleResult(JSONObject resultObject) {
		if (resultObject != null && resultObject.getInteger("code") == 0) {
			JSONObject data = resultObject.getJSONObject("data");
			String accessToken = data.getString("access_token");
			long expiresIn = data.getLongValue("expires_in");
			String refreshToken = data.getString("refresh_token");
			long refreshExpiresIn = data.getLongValue("refresh_token_expires_in");
			int advertiserId = data.getIntValue("advertiser_id");
			// access_token refresh_token 存放到Redis中
			String accessKey = "access_token" + "_" + advertiserId;
			String refreshKey = "refresh_token" + "_" + advertiserId;
			RedisUtils.set(accessKey, accessToken, expiresIn);
			RedisUtils.set(refreshKey, refreshToken, refreshExpiresIn);
			return true;
		}
		return false;
	}

}
